import os

import pandas as pd


class ExcelHandler:
    def __init__(self, file_path):
        # 存储文件路径以便于后续使用
        self.file_path = file_path
        self.ext = os.path.splitext(file_path)[1].lower()

    def read_calibration_data(self):
        """读取Excel中的标定参数"""
        print(self.ext)
        try:
            if self.ext in ['.xls', '.xlsx']:
                df = pd.read_excel(self.file_path, sheet_name='Sheet1', header=0)

            elif self.ext == '.csv':
                # 读取CSV文件，自动推断分隔符
                df = pd.read_csv(self.file_path, header=0, sep=None, engine='python')
            elif self.ext == '.txt':
                # 读取文本文件，自动检测分隔符（支持空格/tab/逗号等）
                df = pd.read_table(self.file_path, header=0, sep='\s+', engine='python')
            else:
                raise ValueError("不支持的文件格式，仅支持xls/xlsx/csv/txt")

            return df.to_dict('records')  # 返回字典列表[1]()
        except Exception as e:
            print(f"Excel读取失败: {str(e)}")
            return []

    def save_measurement_data(self, data):
        """保存测量数据到Excel"""
        try:
            df = pd.DataFrame(data)
            df.to_excel(self.file_path, sheet_name='Sheet3', index=False)
        except Exception as e:
            print(f"Excel保存失败: {str(e)}")
